import os
from sqlalchemy import Column, Integer, String, create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

if os.path.exists('test.db'):
    os.remove('test.db')

engine = create_engine('sqlite:///test.db', echo=True)

Base = declarative_base()


class User(Base):
    __tablename__ = 'User'

    id = Column(Integer, primary_key=True)
    name = Column(String(20))
    age = Column(Integer)


Base.metadata.create_all(engine)

DBSession = sessionmaker(bind=engine)

session = DBSession()
user1 = User(name='wangbo', age=34)
user2 = User(name='dongwei', age=35)
user3 = User(name='wangtianlang', age=3)
user4 = User(name='wangtianlang', age=6)

session.add(user1)
session.add(user2)
session.add(user3)
session.add(user4)


session.commit()
# 关闭session:
session.close()

from sqlalchemy import func
user_all_query = session.query(func.sum(User.age)).filter(User.name=='wangtianlang').scalar()
print(user_all_query)

